<template>
  <div class="p-4 space-y-6 flex flex-col items-center min-h-screen bg-gray-50">
    <h2 class="text-2xl font-bold mb-4 text-blue-400">🖊添加账单</h2>

    <form @submit.prevent="submitBill" class="space-y-4 bg-white shadow p-6 rounded">

      <select v-model="form.categoryType" class="border p-2 w-full rounded" required>
        <option disabled value="">请选择类型</option>
        <option>收入</option>
        <option>支出</option>
      </select>

      <div>
        <div class="mb-1 text-gray-600 font-medium flex justify-between items-center">
          <span>选择分类</span>
          <button type="button" @click="openCustomCatModal()" class="text-blue-500 text-sm">➕ 添加分类</button>
        </div>
        <div class="flex flex-wrap gap-2">
          <div v-for="cat in displayedCategories" :key="cat.id || cat.name" @click="selectCategory(cat)"
            class="cursor-pointer px-3 py-1 rounded text-white flex items-center gap-1 relative"
            :style="{ backgroundColor: cat.color, opacity: form.category === cat.name ? '1' : '0.5' }">
            <span>{{ cat.icon }}</span>
            <span>{{ cat.name }}</span>
            <span
              class="absolute -top-1 -right-1 text-xs cursor-pointer text-white bg-gray-500 rounded-full w-4 h-4 text-center"
              title="编辑" @click.stop="openEditCatModal(cat)">✏️</span>
          </div>
        </div>
      </div>

      <input v-model.number="form.amount" type="number" placeholder="金额" class="border p-2 w-full rounded" required />
      <!-- 修改为 datetime-local -->
      <input v-model="form.date" type="datetime-local" step="1" class="border p-2 w-full rounded" required />
      <input v-model="form.note" placeholder="备注（可选）" class="border p-2 w-full rounded" />

      <div class="flex justify-between">
        <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded">提交</button>
        <button type="button" @click="resetForm" class="text-sm text-gray-500 hover:underline">继续添加</button>
        <button type="button" @click="router.push('/bills')" class="text-sm text-blue-500 hover:underline">返回列表</button>
      </div>
    </form>

    <!-- 添加成功提示 -->
    <div v-if="showSuccess" class="mt-6 bg-green-100 border border-green-300 text-green-700 p-4 rounded">
      添加成功！<br />
      <button @click="router.push('/bills')" class="mt-2 text-blue-600 hover:underline">
        👉 查看账单列表
      </button>
    </div>

    <!-- 添加/编辑分类弹窗 -->
    <div v-if="showCustomCat" class="fixed inset-0 bg-black/30 flex items-center justify-center z-50">
      <div class="bg-white p-6 rounded shadow-lg w-80 space-y-3 relative">
        <h3 class="text-lg font-semibold">{{ editingCat ? '编辑分类' : '添加自定义分类' }}</h3>
        <input v-model="newCat.name" placeholder="分类名" class="border p-2 w-full rounded" />
        <input v-model="newCat.icon" placeholder="图标 (emoji)" class="border p-2 w-full rounded" />
        <div class="flex items-center gap-2">
          <label class="text-sm">颜色：</label>
          <input type="color" v-model="newCat.color" class="w-10 h-10 border rounded" />
        </div>

        <div class="flex justify-between pt-2">
          <button @click="showCustomCat = false" class="text-gray-500 hover:underline">取消</button>
          <button v-if="editingCat" @click="updateCategory"
            class="bg-yellow-500 text-white px-3 py-1 rounded">更新</button>
          <button v-if="editingCat" @click="deleteCategory" class="bg-red-500 text-white px-3 py-1 rounded">删除</button>
          <button v-else @click="addNewCategory" class="bg-green-500 text-white px-3 py-1 rounded">添加</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
const userId = localStorage.getItem('user_id')
const showSuccess = ref(false)

// 工具函数
function toDateTimeString(dt: string): string {
  if (!dt) return ''
  const [date, time] = dt.split('T')
  return `${date} ${time.length === 5 ? time + ':00' : time}`
}

// 默认当前时间带秒
const now = (): string => {
  const d = new Date()
  const pad = (n: number): string => (n < 10 ? '0' + n : n.toString())
  return (
    `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T` +
    `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
  )
}


const form = ref({
  amount: null as number | null,
  categoryType: '', // 支出/收入
  category: '',
  note: '',
  date: now(),      // 默认填当前时间
})

// ======== 分类管理 ========
const customCategories = ref<any[]>([])
const showCustomCat = ref(false)
const editingCat = ref<any | null>(null)
const newCat = ref({
  name: '',
  icon: '📌',
  color: '#3b82f6',
  type: '', // 收入/支出
})

const fetchCategories = async (type: string) => {
  if (!userId || !type) return
  const res = await axios.post('http://127.0.0.1:3000/api/get-categories', {
    user_id: Number(userId),
    type
  })
  customCategories.value = res.data.categories
}

watch(() => form.value.categoryType, async (newType) => {
  if (newType) {
    await fetchCategories(newType)
    form.value.category = ''
  }
})

const displayedCategories = computed(() => {
  return customCategories.value.filter(cat => cat.type === form.value.categoryType)
})

const selectCategory = (cat: any) => {
  form.value.category = cat.name
}

const openCustomCatModal = () => {
  if (!form.value.categoryType) {
    alert('请先选择类型')
    return
  }
  newCat.value = { name: '', icon: '📌', color: '#3b82f6', type: form.value.categoryType }
  editingCat.value = null
  showCustomCat.value = true
}

const openEditCatModal = (cat: any) => {
  editingCat.value = cat
  newCat.value = { ...cat }
  showCustomCat.value = true
}

const addNewCategory = async () => {
  if (!newCat.value.name || !newCat.value.icon || !newCat.value.color) {
    alert('请填写完整分类信息')
    return
  }
  await axios.post('http://127.0.0.1:3000/api/add-category', {
    ...newCat.value,
    user_id: userId,
  })
  showCustomCat.value = false
  await fetchCategories(newCat.value.type)
}

const updateCategory = async () => {
  if (!editingCat.value?.id) return
  await axios.put('http://127.0.0.1:3000/api/update-category', {
    ...newCat.value,
    user_id: userId,
    id: editingCat.value.id,
  })
  showCustomCat.value = false
  editingCat.value = null
  await fetchCategories(newCat.value.type)
}

const deleteCategory = async () => {
  if (!editingCat.value?.id) return
  await axios.delete(`http://127.0.0.1:3000/api/delete-category`, {
    data: { user_id: userId, id: editingCat.value.id },
  })
  showCustomCat.value = false
  editingCat.value = null
  await fetchCategories(newCat.value.type)
}

// ======== 添加账单 ========
const submitBill = async () => {
  if (!userId || !form.value.categoryType || !form.value.category || !form.value.amount) {
    alert('请填写完整信息')
    return
  }
  await axios.post('http://127.0.0.1:3000/api/add-bill', {
    ...form.value,
    user_id: Number(userId),
    categoryType: form.value.categoryType,
    date: toDateTimeString(form.value.date),   // 格式化时间
  })
  showSuccess.value = true
}

const resetForm = () => {
  form.value = {
    amount: null,
    categoryType: '',
    category: '',
    note: '',
    date: now(),
  }
  showSuccess.value = false
}
</script>
